#pragma once
#include "Connection.hpp"
#include "NormalSockHander.hpp"
#include <sys/epoll.h>
#include "epollServer.hpp"
class ConnectionAccepter
{
    public:
    static void Accepter(std::shared_ptr< Connection> connt)
    {
        while (1)
        {
            std::string ip;
            uint16_t port;
            int newsockfd = ns_Util::AcceptConnection(connt->GetFd(), &ip, &port);
            if (newsockfd < 0)
            {
                // 没有发生错误，这里可能出现线程不安全，因为errno是全局变量，如果使用多线程，请将errno设置成线程局部存储
                //同时如果时EAGAIN等非实际错误原因的错误码，请充值其为0
                if (EAGAIN == errno)
                {
                    errno = 0;
                    break;
                }
                else if (EINTR == errno)
                {
                    errno = 0;
                    continue;
                }
                else
                {
                    myService::lg(myService::Log::Error, "Accepter:accept error:获取一个新连接错误\n");
                    break;
                }
            }
            else
            {
                myService::lg(myService::Log::Info, "Accepter:accept a new connection:ip=%s,port=%d\n", ip.c_str(), port);
                ns_Util::SetNonBlock(newsockfd);
                auto newConnection = ConnectionMaker::BuildNormalConnection(newsockfd,
                                                        connt->_R,
                                                        EPOLLIN | EPOLLOUT|EPOLLHUP, 
                                                        NormalSockHander::Recv,NormalSockHander::Send,NormalSockHander::Excepter);
                connt->_R->AddConnection(newConnection);
            }
        }
    }
};